package com.activitiFlow.service;

import java.util.Map;
import java.util.Set;

import org.activiti.engine.impl.bpmn.behavior.UserTaskActivityBehavior;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.vx.FlowCode;
import com.vx.service.IProcessInstanceEntryService;

@Service("runtimeFlow")
public class RuntimeFlow {

	@Autowired
	private IRuntimeBiz runtimeBiz;
	
	@Autowired
	private IRepositoryBiz repositoryBiz;
	
	@Autowired
	private IProcessInstanceEntryService processInstanceEntryService;
	
	@Autowired
	private ITaskBiz taskBiz;
	

	public int startPross(String borrowId, String userCode, String _buinessKey,String candidateUsers) {
		//启动流程
		ProcessInstance processInstance=runtimeBiz.saveStartProcess(borrowId,_buinessKey,userCode);
		//启动流程后将流程中的提交申请节点自动完成，因为自己提交的任务，不需要再在流程中审批一次
		ExecutionEntity executionEntity=(ExecutionEntity) processInstance;
		String taskId=executionEntity.getTasks().get(0).getId();
		//填写默认的审批信息
		Authentication.setAuthenticatedUserId(userCode);
		taskBiz.addComment(taskId, executionEntity.getProcessInstanceId(),FlowCode.STARTFLOWMESSAGE);
		//提交“提交申请”的审批信息
		taskBiz.saveSubmitTask(taskId, null);
		
		//判断流程中的办理人时何种设置方式：类监听 或者 通过流程变量设置
		Task task=taskBiz.getTaskByTaskProcessInstanceId(executionEntity.getProcessInstanceId());
		ActivityImpl activityNode=processInstanceEntryService.getRunActivityNode(task.getId());
		Set userexpressionSet=((UserTaskActivityBehavior)activityNode.getActivityBehavior()).getTaskDefinition().getCandidateUserIdExpressions();
		if(userexpressionSet!=null && userexpressionSet.size()>0){
			//流程中的办理人是走的设置流程变量方式，设置下一环节的办理人
			if(candidateUsers!=null){
				String[] candidateUserStr=StringUtils.split(candidateUsers, ",");
				for (int i = 0; i < candidateUserStr.length; i++) {
					taskBiz.addCandidateUser(task.getId(),candidateUserStr[i]);
				}
			}
			taskBiz.deleteCandidateUser(task.getId(),userCode);
		}
		return FlowCode.FLOW_START;
	}
}
